package com.godyao.mvcframework.servlet;

import com.godyao.mvcframework.annotations.*;
import com.godyao.mvcframework.pojo.Handler;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author godyao
 */
public class DispacherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String, Object> singletons = new HashMap<>();

    public static List<Handler> getHandlerMapping() {
        return handlerMapping;
    }

    private static List<Handler> handlerMapping = new ArrayList<>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = getHandler(req);

        Map<String, String[]> parameterMap = req.getParameterMap();
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        Object[] args = new Object[parameterTypes.length];
        Method method = handler.getMethod();
        for (Map.Entry<String, Integer> stringIntegerEntry : handler.getParamIndexMapping().entrySet()) {
            if (!parameterMap.containsKey(stringIntegerEntry.getKey())) continue;
            String[] strings = parameterMap.get(stringIntegerEntry.getKey());
            Integer index = stringIntegerEntry.getValue();
            String value="";
            if (strings.length == 0) continue;
            for (String string : strings) {
                value += ","+string;
            }
            String paramValue = value.substring(1);
            args[index] = Integer.valueOf(paramValue);
        }
        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        args[requestIndex] = req;
        args[responseIndex] = resp;
        try {
            Object invoke = method.invoke(handler.getControllerObj(), args);
            resp.setCharacterEncoding("gb2312");
            resp.getWriter().write(invoke.toString());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    protected Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {return null;}
        String requestURI = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            if (handler.getUrlPattern().matcher(requestURI).matches()) {
               return handler;
            }
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1.加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        // 2.扫描注解类和扫描注解
        doScan(properties.getProperty("scanPackage"));

        // 3.初始化Bean对象（基于注解实现ioc容器）
        doInstance();

        // 4.实现依赖注入
        doAutowired();

        // 5.构造一个HandlerMapping处理器映射器，将配置好的url和Method建立联系
        initHandlerMapping();

        System.out.println("自定义mvc初始化完成");
    }

    private void initHandlerMapping() {
        if (singletons.isEmpty()) {return;}
        for (Map.Entry<String, Object> stringObjectEntry : singletons.entrySet()) {
            Object object = stringObjectEntry.getValue();
            Class<?> aClass = object.getClass();
            if (!aClass.isAnnotationPresent(Controller.class)) {
               continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(RequestMapping.class)) {
                baseUrl = aClass.getAnnotation(RequestMapping.class).value().trim();
            }
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                if (declaredMethod.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping annotation = declaredMethod.getAnnotation(RequestMapping.class);
                    String methodUrl = annotation.value().trim();
                    String url = baseUrl + methodUrl;
                    // 将method所有方法和信息封装成一个handler
                    Handler handler = new Handler(object, declaredMethod, Pattern.compile(url));

                    // 计算方法的参数位置
                    Parameter[] parameters = declaredMethod.getParameters();
                    for (int i = 0; i < parameters.length; i++) {
                        Parameter parameter = parameters[i];
                        if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                            // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                            handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                        } else {
                            handler.getParamIndexMapping().put(parameter.getName(), i);
                        }
                    }
                    handlerMapping.add(handler);
                }
            }
        }
    }

    private void doAutowired() {
        try {
            for (Map.Entry<String, Object> stringObjectEntry : singletons.entrySet()) {
                Object object = stringObjectEntry.getValue();
                Class<?> aClass = object.getClass();
                Field[] declaredFields = aClass.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    if (declaredField.isAnnotationPresent(Autowire.class)) {
                        Autowire annotation = declaredField.getAnnotation(Autowire.class);
                        String value = annotation.value().trim();
                        Class<?> type = declaredField.getType();
                        String dependBeanName = "".equals(value) ? type.getName() : value;
                        declaredField.setAccessible(true);
                        declaredField.set(object, singletons.get(dependBeanName));

                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    private void doInstance()  {
        if (classNames.isEmpty()) {return;}
        try {
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(Controller.class)) {
                    Controller controllerAnno = aClass.getAnnotation(Controller.class);
                    String value = controllerAnno.value().trim();
                    String beanName = "".equals(value) ? lowerFirstWord(aClass.getSimpleName()) : value;
                    singletons.put(beanName, aClass.getDeclaredConstructor().newInstance());
                } else if (aClass.isAnnotationPresent(Service.class)) {
                    Service serviceAnno = aClass.getAnnotation(Service.class);
                    String value = serviceAnno.value().trim();
                    String beanName = "".equals(value) ? lowerFirstWord(aClass.getSimpleName()) : value;
                    Object o = aClass.getDeclaredConstructor().newInstance();
                    singletons.put(beanName, o);

                    // 将其实现的接口在注册一份
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        // beanName为全限定类名
                        singletons.put(anInterface.getName(), o);
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String lowerFirstWord(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if (chars.length > 0 && chars[0] >= 'A' && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return chars.toString();
    }

    private void doScan(String scanPackage) {
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String scanPackageToPath = scanPackage.replaceAll("\\.", "/");
        String scanPath = rootPath + scanPackageToPath;
        File pack = new File(scanPath);
        File[] files = pack.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                doScan(scanPackage+"."+file.getName());
            }else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }

    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation.replaceAll("classpath\\*:", ""));
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
